// 简单node服务器
const http = require('http')
const path = require('path')
const {
    readFile,
    stat
} = require('fs')
http.createServer(function (req, res) {
    const myUrl = new URL("http://localhost:8864" + req.url)
    let pathname = path.resolve(`./${myUrl.pathname}`)
    if (path.extname(pathname) == "") {
        pathname += "\\index.html";
    }
    console.log(pathname)
    stat(pathname, (err, data) => {
        if (err) {
            res.writeHead(404, {
                "Content-Type": "text/html"
            });
            res.end("<h1>404 Not Found</h1>");
        } else {
            switch (path.extname(pathname)) {
                case ".html":
                    res.writeHead(200, {
                        "Content-Type": "text/html"
                    });
                    break;
                case ".js":
                    res.writeHead(200, {
                        "Content-Type": "text/javascript"
                    });
                    break;
                case ".css":
                    res.writeHead(200, {
                        "Content-Type": "text/css"
                    });
                    break;
                case ".gif":
                    res.writeHead(200, {
                        "Content-Type": "image/gif"
                    });
                    break;
                case ".jpg":
                case ".jpeg":
                    res.writeHead(200, {
                        "Content-Type": "image/jpeg"
                    });
                    break;
                case ".png":
                    res.writeHead(200, {
                        "Content-Type": "image/png"
                    });
                    break;
                default:
                    res.writeHead(200, {
                        "Content-Type": "application/octet-stream"
                    });
            }
            readFile(pathname, function (err, data) {
                res.end(data);
            });
        }
    })
}).listen(8864);